#include <tinx/task.h>
#include <tinx/interrupt.h>
#include <tinx/printk.h>
#include <tinx/io.h>

#define PIT_CHAN0_REG 0X40
#define PIT_CHAN2_REG 0X42
#define PIT_CTRL_REG 0X43

#define HZ 100
#define OSCILLATOR 1193182
#define CLOCK_COUNTER (OSCILLATOR / HZ)
#define JIFFY (1000 / HZ)

volatile u32 jiffies = 0;
u32 jiffy = JIFFY;

void clock_handler(u8 vector)
{
    send_eoi(vector);

    jiffies++;

    task_t *task = running_task();

    if (!task->ticks)
    {
        schedule();
    }
    else
    {
        task->ticks--;
        task->jiffies++;
    }
}

void pit_init()
{
    outb(PIT_CTRL_REG, 0b00110100);
    outb(PIT_CHAN0_REG, CLOCK_COUNTER & 0xff);
    outb(PIT_CHAN0_REG, (CLOCK_COUNTER >> 8) & 0xff);
}

void clock_init()
{
    pit_init();

    set_interrupt_mask(IRQ_CLOCK, true);
    set_interrupt_handler(0x20, clock_handler);
}